import { Button, Card, Form, Input, message, Select, Space } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import React, { useCallback, useEffect, useState } from "react";
import Table, { ColumnsType } from "antd/lib/table";
import {
  ProvinceItems,
  ReqGetHospitalListItems,
} from "@/api/hospital/model/hospitalListTypes";
import {
  ReqGetCityOrDistRict,
  ReqGetHospitalList,
  ReqGetHostype,
  ReqGetProvince,
  ReqUpdateStatus,
} from "@/api/hospital/hospitalList";
import { useNavigate } from "react-router-dom";

let { Option } = Select;

export default function HospitalList() {
  // 表单的onFinish事件
  let finish = () => {
    let res = form.getFieldsValue();
    setFields(res);
  };
  let [form] = Form.useForm();
  // 声明省的状态
  let [province, setProvince] = useState<ProvinceItems>([]);
  // 声明市的状态
  let [city, setCity] = useState<ProvinceItems>([]);
  // 声明区县的状态
  let [district, setDistrict] = useState<ProvinceItems>([]);
  // 声明医院类型的状态
  let [hostype, setHostype] = useState<ProvinceItems>([]);
  // 声明当前页码的状态
  let [current, setCurrent] = useState(1);
  // 声明一个总数的状态
  let [total, setTotal] = useState(0);
  // 声明一个每页显示数量的状态
  let [pageSize, setPageSize] = useState(5);
  // 声明一个医院列表的状态
  let [hospital, setHospital] = useState<ReqGetHospitalListItems>([]);
  // 声明一个加载的状态
  let [loading, setLoading] = useState(false);
  // 设置fields的状态
  let [fields, setFields] = useState({
    cityCode: undefined,
    districtCode: undefined,
    hoscode: undefined,
    hosname: undefined,
    hostype: undefined,
    provinceCode: undefined,
    status: undefined,
  });
  let navigate = useNavigate();
  useEffect(() => {
    // 获取省列表
    let getProvince = async () => {
      let result = await ReqGetProvince();
      setProvince(result);
    };
    getProvince();
  }, []);

  useEffect(() => {
    // 获取医院类型
    let getHostype = async () => {
      let result = await ReqGetHostype();
      setHostype(result);
    };
    getHostype();
  }, []);

  // 选择省之后通过onChange事件获取到下拉选项的value值
  let getCity = async (provinceId: number) => {
    if (!provinceId) return;
    // 获取城市之前先清空城市和区县下拉框
    form.setFieldsValue({ cityCode: undefined, districtCode: undefined });
    // 更新市的状态
    setCity([]);
    // 更新区的状态
    setDistrict([]);
    // 获取城市列表
    let city = await ReqGetCityOrDistRict(provinceId);
    setCity(city);
  };

  // 选择市之后通过onChange事件获取到下拉选项的value值
  let getDistrict = async (cityId: number) => {
    // 获取城市之前先清空区县下拉框
    form.setFieldsValue({ districtCode: undefined });
    // 清空区的状态
    setDistrict([]);
    // 获取区县列表
    let district = await ReqGetCityOrDistRict(cityId);
    setDistrict(district);
  };
  // 表格结构
  let columns: ColumnsType<any> = [
    {
      title: "序号",
      width: 80,
      render: (value, row, index) => {
        return index + 1;
      },
    },
    {
      title: "医院Logo",
      dataIndex: "logoData",
      render: (value) => {
        return (
          <img width={100} alt="" src={`data:image/gif;base64,${value}`}></img>
        );
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      render: (value) => {
        return value.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      render: (value) => {
        return value.param.fullAddress;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      render: (value) => {
        return value ? "已上线" : "已下线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      fixed: "right",
      width: 250,
      render: (value) => {
        console.log(value)
        return (
          <Space>
            <Button
              type="primary"
              onClick={() => {
                navigate(`/syt/hospital/hospitallist/show/${value.id}`);
              }}
            >
              查看
            </Button>
            <Button
              type="primary"
              onClick={() => {
                navigate(
                  `/syt/hospital/hospitallist/schedule/${value.hoscode}`
                );
              }}
            >
              排班
            </Button>
            <Button type="primary" onClick={ async ()=>{
              // 更新
              await ReqUpdateStatus(value.id,value.status ? 0 : 1);
              message.success('成功')
              // 刷新列表
              let newHospital = hospital.map(item=>{
                if(item.id === value.id){
                  item.status = item.status ? 0 : 1 ;
                }
                return item;
              })
              setHospital(newHospital);
            }} >{value.status ? '下线' : '上线'}</Button>
          </Space>
        );
      },
    },
  ];


  let getHospitalList = useCallback(async () => {
    setLoading(true);
    // 获取表单数据
    let fields = form.getFieldsValue();
    let result = await ReqGetHospitalList({
      page: current,
      limit: pageSize,
      ...fields,
    });
    // 更新医院状态
    setHospital(result.content);
    // 更新总数状态
    setTotal(result.totalElements);
    setLoading(false);
  }, [current, pageSize, fields]);//依赖于当前页码,每页显示数,表单数据

  useEffect(() => {
    getHospitalList();
  }, [getHospitalList]);
  return (
    <Card>
      <Form layout="inline" onFinish={finish} form={form}>
        <Form.Item name="provinceCode" style={{ width: 250, marginBottom: 20 }}>
          <Select placeholder="请选择省" onChange={getCity}>
            {province.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="cityCode" style={{ width: 250 }}>
          <Select placeholder="请选择市" onChange={getDistrict}>
            {city.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="districtCode" style={{ width: 250 }}>
          <Select placeholder="请选择区">
            {district.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>
        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>
        <Form.Item name="hostype">
          <Select placeholder="医院类型" style={{ width: 250 }}>
            {hostype.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="status" style={{ width: 250 }}>
          <Select placeholder="医院状态">
            <Option value={1}>已上线</Option>
            <Option value={0}>已下线</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
            查询
          </Button>
        </Form.Item>
        <Form.Item>
          <Button
            onClick={() => {
              form.resetFields();
              setFields(fields);
              setCurrent(1);
            }}
          >
            清空
          </Button>
        </Form.Item>
      </Form>
      <div className="h-20"></div>
      <Table
        loading={loading}
        scroll={{ x: 1700 }}
        rowKey="id"
        dataSource={hospital}
        columns={columns}
        bordered
        pagination={{
          total,
          pageSize,
          current,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: [5, 10, 15],
          showTotal(total, range) {
            return `总共:${total}条`;
          },
          // 当页码与每页数量发生变化时,触发事件
          onChange: (page: number, pageSize: number) => {
            setCurrent(page);
            setPageSize(pageSize);
          },
        }}
      />
    </Card>
  );
}
